package org.marsdonne.commons;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class FeignRequestInterceptor implements RequestInterceptor {
    private static final String AuthorizationHeader = "Authorization";

    private static final Logger LOGGER = LoggerFactory.getLogger(FeignRequestInterceptor.class);

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader(AuthorizationHeader);
            if (StringUtils.hasText(token)) {
                template.header(AuthorizationHeader, token);
            } else {
                LOGGER.warn("Failed to get {} from {}", AuthorizationHeader, HttpServletRequest.class.getSimpleName());
            }
        } else {
            LOGGER.warn("Failed to get {}", ServletRequestAttributes.class.getSimpleName());
        }
    }
}
